<?php

declare (strict_types=1);

namespace app\common\model\admin;

use app\common\enum\file\Storage as StorageEnum;
use app\common\enum\Setting as SettingEnum;
use app\common\enum\setting\sms\Scene as SettingSmsSceneEnum;
use app\common\library\helper;
use cores\BaseModel;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Model;

/**
 * 管理后台系统设置模型
 * Class Setting
 * @package app\common\model
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'admin_setting';

    /**
     * 获取指定项设置
     * @param string $key
     * @return array|mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getItem(string $key)
    {
        $data = self::getAll();
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 全局缓存: 系统设置
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAll(): array
    {
        $model = new static;
        if (!$data = Cache::get("admin_setting")) {
            // 获取平台设置列表
            $setting = $model->getList();
            $data = $setting->isEmpty() ? [] : helper::arrayColumn2Key($setting->toArray(), 'key');
            // 写入缓存中
            Cache::tag('cache')->set("admin_setting", $data);
        }
        // 合并默认设置
        return array_merge_multiple($model->defaultData(), $data);
    }

    /**
     * 获取平台设置列表
     * @return Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getList()
    {
        return $this->select();
    }

    /**
     * 默认配置
     * @return array
     */
    public function defaultData(): array
    {
        return [
            // 上传设置
            SettingEnum::STORAGE => [
                'key' => SettingEnum::STORAGE,
                'describe' => '上传设置',
                'values' => [
                    'default' => StorageEnum::LOCAL,
                    'engine' => [
                        StorageEnum::LOCAL => null,
                        StorageEnum::QINIU => [
                            'bucket' => '',
                            'access_key' => '',
                            'secret_key' => '',
                            'domain' => 'http://'
                        ],
                        StorageEnum::ALIYUN => [
                            'bucket' => '',
                            'access_key_id' => '',
                            'access_key_secret' => '',
                            'domain' => 'http://'
                        ],
                        StorageEnum::QCLOUD => [
                            'bucket' => '',
                            'region' => '',
                            'secret_id' => '',
                            'secret_key' => '',
                            'domain' => 'http://'
                        ],
                    ]
                ],
            ],
            // 短信通知
            SettingEnum::SMS => [
                'key' => SettingEnum::SMS,
                'describe' => '短信通知',
                'values' => [
                    'default' => 'aliyun',
                    // 短信服务渠道
                    'engine' => [
                        // 阿里云
                        'aliyun' => [
                            'name' => '阿里云短信',
                            'website' => 'https://dysms.console.aliyun.com/dysms.htm',
                            'AccessKeyId' => '',
                            'AccessKeySecret' => '',
                            'sign' => 'xxx平台'   // 短信签名
                        ],
                        // 腾讯云
                        'qcloud' => [
                            'name' => '腾讯云短信',
                            'website' => 'https://console.cloud.tencent.com/smsv2',
                            'SdkAppID' => '',
                            'AccessKeyId' => '',
                            'AccessKeySecret' => '',
                            'sign' => 'xxx平台'   // 短信签名
                        ],
                        // 七牛云
                        'qiniu' => [
                            'name' => '七牛云短信',
                            'website' => 'https://portal.qiniu.com/sms/dashboard',
                            'AccessKey' => '',
                            'SecretKey' => '',
                            'sign' => 'xxx平台'   // 短信签名
                        ],
                    ],
                    // 短信通知场景
                    'scene' => [
                        // 短信验证码
                        SettingSmsSceneEnum::CAPTCHA => [
                            'name' => '短信验证码 (通知用户)',    // 场景名称
                            'isEnable' => false,     // 是否开启
                            'templateCode' => '',    // 模板ID
                            'content' => '验证码%s，您正在进行身份验证，打死不要告诉别人哦！',
                            'variables' => [
                                'aliyun' => ['${code}'],
                                'qiniu' => ['${code}'],
                                'qcloud' => ['{1}'],
                            ]
                        ],
                        // 新付款订单
                        SettingSmsSceneEnum::ORDER_PAY => [
                            'name' => '新付款订单 (通知机构)',   // 场景名称
                            'isEnable' => false,    // 是否开启
                            'templateCode' => '',   // 模板ID
                            'acceptPhone' => '',    // 接收手机号
                            'content' => '您有一条新订单，订单号为：%s，请注意查看',
                            'variables' => [
                                'aliyun' => ['${order_no}'],
                                'qiniu' => ['${order_no}'],
                                'qcloud' => ['{1}'],
                            ]
                        ],
                    ]
                ],
            ],

            // 账户注册设置
            SettingEnum::REGISTER => [
                'key' => SettingEnum::REGISTER,
                'describe' => '账户注册设置',
                'values' => [
                    'registerMethod' => 10,   // 默认注册方式: 10=>手机号+短信验证码
                    'isOauthMpweixin' => 1,   // 是否开启微信小程序一键授权登录
                    'isForceBindMpweixin' => 1,   // 客户端是否强制绑定手机号(微信小程序)
                    'isManualBind' => 1,   // 个人中心页显示手动绑定手机号
                ],
            ],
        ];
    }

    /**
     * 获取设置项信息
     * @param string $key
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function detail(string $key)
    {
        $query = (new static)->getNewQuery();
        return $query->where('key', '=', $key)->find();
    }

    /**
     * 获取器: 转义数组格式
     * @param $value
     * @return mixed
     */
    public function getValuesAttr($value)
    {
        return helper::jsonDecode($value);
    }

    /**
     * 修改器: 转义成json格式
     * @param $value
     * @return string
     */
    public function setValuesAttr($value): string
    {
        return helper::jsonEncode($value);
    }
}
